<?php
// +----------------------------------------------------------------------
// | When work is a pleasure, life is a joy!
// +----------------------------------------------------------------------
// | User: ShouKun Liu  |  Email:24147287@qq.com  | Time:2016/12/10 23:56
// +----------------------------------------------------------------------
// | TITLE:基础类
// +----------------------------------------------------------------------

namespace apps\backend;

use Yii;
use yii\helpers\Url;
use yii\web\Controller;


/**
 * Class BaseController
 * @package backend\controllers
 */
class BaseController extends \xing\ace\controllers\BaseController
{
    public $userId; //当前登录用户id
    public $username; //当前登录用户名


    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /*
     * 页面成功跳转
     * $param string $msg 提示信息
     * $param string $url 跳转地址
     */
    public function alertSuccess($msg,$url){
        return $this->render('@app/views/public/alert', ['msg' => $msg, 'url' => $url, 'type' => 'success']);
    }
    /*
     * 页面失败跳转
     * $param string $msg 提示信息
     * $param string $url 跳转地址
     */
    public function alertError($msg,$url){
        return $this->render('@app/views/public/alert', ['msg' => $msg, 'url' => $url, 'type' => 'error']);
    }

    public function beforeAction($action)
    {
        parent::beforeAction($action);
        if ($action->id == 'update' && empty($_POST)) {
//            hr(Yii::$app->request->getReferrer());
            Yii::$app->cache->set('backend:UpdateLastPage', Yii::$app->request->getReferrer());
        }

        if ($this->isLogin()) {
            $this->userId = Yii::$app->user->identity->getId(); //获取后台管理员ID

            if (!$this->verifyRule($this->route)) {
                die('你没有权限');
            }
        }
        return true;
    }

    public function redirectUpdateLastPage()
    {
        return $this->redirect(Yii::$app->cache->get('backend:UpdateLastPage') ?: 'index');
    }

    /**
     * 验证登入
     * @return bool
     */
    protected function isLogin()
    {
        if (Yii::$app->user->isGuest) {
            $allowUrl = ['site/logout', 'admin/site/login'];
            if (in_array($this->route, $allowUrl) == false) {
                $loginUrl = Url::toRoute('/admin/site/login');
                header("Location: $loginUrl");
                exit();
            } else {
                return false;
            }
        } else {
            return true;
        }

    }


}

